package com.boco.service.impl;

import com.boco.common.pojo.ResourceData;
import com.boco.service.FileUpDownService;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @author pandengke/pdkkpdk@163.com
 * @date 2018/11/7
 */
@Service("simpleFileUpDownService")
public class FileUpDownServiceImpl implements FileUpDownService {

    private String uploadDir;

    public FileUpDownServiceImpl() {
        updateUploadDir();
    }

    private void updateUploadDir() {
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath(), "static/images/upload/");
            path.mkdirs();
            this.uploadDir = path.getAbsolutePath();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResourceData uploadForEntity(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        File savedFile = new File(uploadDir, UUID.randomUUID().toString() + "." + suffix);
        try {
            file.transferTo(savedFile);
            ResourceData resourceData = new ResourceData();
            resourceData.setExt(suffix);
            resourceData.setFileName(savedFile.getName());
            resourceData.setLength(savedFile.length());
            resourceData.setUrl("/manage/download?filename=" + resourceData.getFileName());
            return resourceData;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public InputStream download(String filename) {
        File savedFile = new File(uploadDir, filename);
        assert savedFile.exists();
        try {
            return new FileInputStream(savedFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
